package com.cskaoyan.market.util;

import com.cskaoyan.market.db.domain.MarketGoods;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author lanch
 * @since 2023/05/07 21:55
 */
public class GetRequestBody {
    //获取请求体里面的参数，传入一个对象，将json字符串里面的属性赋值给该对象，并返回该对象
    public static Object getReqBodyObject(HttpServletRequest req,Object object) throws IOException {
        //    请求参数为json字符串，需要到请求体里面获取
        String reqBodyString = getReqBodyString(req);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        object = objectMapper.readValue(reqBodyString,object.getClass());
        return object;
    }
    //获取请求体里面的参数，转化为json格式的字符串
    public static String getReqBodyString(HttpServletRequest req) throws IOException {
        //System.out.println("login");
        //请求参数位于请求体中，所以我们需要自己主动的去解析请求体
        ServletInputStream inputStream = req.getInputStream();
        //ByteArrayOutputStream和FileOutputStream的区别就是一个写出到数组，一个写出到文件，除此之外，操作上完全一模一样
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int length = 0;
        byte[] bytes = new byte[1024];
        while ((length = inputStream.read(bytes)) != -1){
            byteArrayOutputStream.write(bytes, 0, length);
        }
        //数组里面的数据转换成字符串
        // {"username":"admin123","password":"admin123"}
        //处理起来有两种方式
        String requestBody = byteArrayOutputStream.toString("utf-8");
        return requestBody;
    }
}
